<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------
namespace User\Model;
use Think\Model;
/**
 * 会员模型
 */
class UcenterSocialModel extends Model{
	/**
	 * 数据表前缀
	 * @var string
	 */
	protected $tablePrefix = UC_TABLE_PREFIX;

	/**
	 * 数据库连接
	 * @var string
	 */
	protected $connection = UC_DB_DSN;

	/**
	 * 用户登录社会化认证
	 * @param  string  $username 用户名
	 * @param  string  $social_id 社会化ID
	 */
	public function socialLogin($username,$social_id,$media_type,$access_token,$expires_in){
		$map = array();
		$map['social_id'] = $social_id;

		/* 获取用户数据 */
		$user = $this->where($map)->find();
		if(is_array($user)){
			if($user['status']) {
				$this->updateLogin($user['id']); //更新用户登录信息
				return $user['id']; //登录成功，返回用户ID
			}else {
				return -1; //用户不存在或被禁用
			}
		} else { // 第一次社会化登录注册用户
			/* 添加用户 */
			$data = array();
			$data['username'] = $username;
			$data['social_id'] = $social_id;
			$data['media_type'] = $media_type;		
			$data['access_token'] = $access_token;		
			$data['expires_in'] = $expires_in;
			$data['status'] = 1;
			if($this->create($data)){
				$uid = $this->add();
				return $uid ? $uid : 0; //0-未知错误，大于0-注册成功
			} else {
				return $this->getError(); //错误详情见自动验证注释
			}
		}
	}

	/**
	 * 更新用户登录信息
	 * @param  integer $uid 用户ID
	 */
	protected function updateLogin($uid){
		$data = array(
			'id'              => $uid,
			'last_login_time' => NOW_TIME,
			'last_login_ip'   => get_client_ip(1),
		);
		$this->save($data);
	}

	/**
	 * 获取社会化用户信息
	 * @param  string  $uid         用户ID或用户名
	 * @param  boolean $is_username 是否使用用户名查询
	 * @return array                用户信息
	 */
	public function info($uid, $is_username = false){
		$map = array();
		if($is_username){ //通过用户名获取
			$map['username'] = $uid;
		} else {
			$map['id'] = $uid;
		}

		$user = $this->where($map)->field('id,username,media_type,status')->find();
		if(is_array($user) && $user['status'] = 1){
			return array($user['id'], $user['username'], $user['media_type']);
		} else {
			return -1; //用户不存在或被禁用
		}
	}
}
